package com.duowan.cms.intf.gamelib;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.DynaBean;
import org.springframework.stereotype.Service;
import org.springframework.util.SerializationUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;

import com.duowan.cms.intf.Constants;
import com.duowan.cms.common.exception.BaseCheckedException;
import com.duowan.cms.common.util.JsonUtil;
import com.duowan.cms.common.util.NetUtil;

@Service("gameLibRemoteService")
public class GameLibServiceImpl implements GameLibRemoteService {
	
	/**
	 * 从接口获取最新数据并写入缓存
	 * @return
	 * @throws BaseCheckedException 
	 */
	public  String getJsonFromKuAPI(String gameName) throws BaseCheckedException{
		Map<String, String> postParamsMap = new HashMap<String, String>(); 
		postParamsMap.put("m","getGameCard2");
		postParamsMap.put("cnName", gameName);
		//Constants.GAME_CARD_URL=http://ku.duowan.com/api/ku.jsp
		String mesg =NetUtil.postHttpRequest( postParamsMap, 
		        Constants.GAME_CARD_URL, Constants.EXPIRE_SECONDS);
		String[] data = mesg.split("\n");
		if(!"201".equals(data[0])){
		    throw new BaseCheckedException("ku_api_fail", mesg);
		}
		logger.info("从游戏库返回的数据：" + data[3]);
		return data[3];
	}
	
	@Override
	public List<GameInfo> getAll() throws BaseCheckedException {
		String mesg =NetUtil.postHttpRequest( new HashMap(), 
			Constants.GAME_API_URL, Constants.EXPIRE_SECONDS);
		String jsonStr = mesg.split("\n")[3];
		JSONArray jsonArr = JSONArray.fromObject(jsonStr);
		GameInfo obj = null;
		List<GameInfo> gameInfoList = new ArrayList<GameInfo>();
		for(int i=0;i<jsonArr.size();i++)  {
			obj = (GameInfo) JSONObject.toBean(jsonArr.getJSONObject(i), GameInfo.class);
			gameInfoList.add(obj);
		}
		return gameInfoList;
	}

	@Override
	public String getGameCardInfo(String gameName) throws BaseCheckedException {
		return this.getJsonFromKuAPI(gameName);
	}
	
	public static void main(String[] args) {
        String str = "{" + 
        "\"actStateId\":2," + 
        "\"bbsUrl\":\"http://bbs.duowan.com/forum-396-1.html\"," + 
        "\"channelUrl\":\"http://xa.duowan.com\"," + 
        "\"clientSize\":\"未知\"," + 
        "\"clientUrl\":\"\"," + 
        "\"cnName\":\"笑傲江湖\"," + 
        "\"deCo\":\"完美\"," + 
        "\"deCoList\":[\"完美\"]," + 
        "\"evaluationUrl\":\"\"," + 
        "\"gameID\":11308," + 
        "\"homePageUrl\":\"http://xa.wanmei.com/\"," + 
        "\"kaInfo\":\"1207457人已预订\"," + 
        "\"kaStatus\":\"预订\"," + 
        "\"kaUrl\":\"http://ka.duowan.com/8068.html\"," + 
        "\"navInfos\":[{\"gameID\":11308,\"navID\":1401112,\"title\":\"游戏专区\",\"url\":\"http://xa.duowan.com/\",\"used\":true,\"weight\":1},{\"gameID\":11308,\"navID\":9496960,\"title\":\"笑傲江湖电影\",\"url\":\"http://xa.duowan.com/yingshi/index.html\",\"used\":true,\"weight\":1},{\"gameID\":11308,\"navID\":71283033,\"title\":\"笑傲江湖小说\",\"url\":\"http://xa.duowan.com/xiaoshuo/index.html\",\"used\":true,\"weight\":1}]," + 
        "\"opCo\":\"完美\"," + 
        "\"opCoList\":[\"完美\"]," + 
        "\"picNums\":253," + 
        "\"picUrl\":\"x/xajh.JPG\"," + 
        "\"region\":\"中国大陆\"," + 
        "\"starNum\":0," + 
        "\"statusInfo\":\"研发\"," + 
        "\"subject\":\"武侠.小说改编\"," + 
        "\"subjectList\":[\"武侠.小说改编\"]," + 
        "\"type\":\"角色扮演\"," + 
        "\"typeList\":[\"角色扮演\"]," + 
        "\"urlID\":\"xajh\"," + 
        "\"videoNums\":16," + 
        "\"visual\":\"3D\"," + 
        "\"visualList\":[\"3D\"]}";
        GameCardInfo gameCardInfo = JsonUtil.jsonString2JavaBean(GameCardInfo.class, str);
    }

	/**
	 * 通过游戏名字获取游戏卡的信息
	 */
	@Override
	public GameInfo getGameInfoByName(String name) throws BaseCheckedException {
		JSONArray jsonArr = JSONArray.fromObject(this.getAll());
		GameInfo obj = null;
		for(int i=0;i<jsonArr.size();i++)  {
			obj = (GameInfo) JSONObject.toBean(jsonArr.getJSONObject(i), GameInfo.class);
            if( obj!=null && name.equals(obj.getGameName()) ){
            	return obj;
            }
        }
		return null;
	}
	
    

	/**
	 * 功能描述：	发送资讯到游戏库系统（发送游戏的文章title和文章url）
	 * 		URL:		http://ku.duowan.com/api/ku.jsp
	 * 		接收参数：	m=saveGameMessage	（必填）
								cnName=游戏名字		（必填）
								title=文章标题		 (必填)
								url=文章链接		 (必填)
		参考链接：	http://ku.duowan.com/api/ku.jsp?m=saveGameMessage&cnName=%E5%80%A9%E5%A5%B3%E5%B9%BD%E9%AD%82&title=%E6%B8%B8%E6%88%8F%E4%B8%93%E5%8C%BA&url=http://qn.duowan.com/
	 */
	@Override
	public void sendArticle(String gameName,String articleTitle, String articleUrl) throws BaseCheckedException {
		Map<String, String> postParamsMap = new HashMap<String, String>(); 
		postParamsMap.put("m","saveGameMessage");
		postParamsMap.put("cnName", gameName);
		postParamsMap.put("title", articleTitle);
		postParamsMap.put("url", articleUrl);
		NetUtil.postHttpRequest(postParamsMap, Constants.GAME_CARD_URL, Constants.EXPIRE_SECONDS);
	}

}
